﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RelatorioDinamico.WebUI.Models;

namespace System.Web
{
    public static class WebExtension
    {
        public static IEnumerable<SelectListItem> ToSelectList(Type type, bool useIntValue = true
            , bool useDescriptionValue = true, string defaultOption = "Selecione")
        {
            var values = new List<SelectListItem>();

            foreach (var e in Enum.GetValues(type))
            {
                values.Add(new SelectListItem
                {
                    Value = useIntValue ? Enum.Format(type, Enum.Parse(type, e.ToString()), "d") : e.ToString(),
                    Text = useDescriptionValue ? SystemExtensions.GetDescription(e) : e.ToString()
                });
            }

            if (!defaultOption.IsNullOrEmpty())
            {
                if (Enum.IsDefined(type, defaultOption))
                    values.Find(x => x.Text == defaultOption).Selected = true;
                else
                    values.Insert(0, new SelectListItem { Selected = true, Text = defaultOption });
            }

            return values;
        }
    }
}